/**
 * Project Name:fastPlat
 * File Name:DepartmentController.java
 * Package Name:com.fast.cms.web.controller.admin
 * Date:2014年12月17日下午2:34:53
 * Copyright (c) 2014, lsflu@126.com All Rights Reserved.
 *
*/

package com.fast.user.web.controller.dept;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fast.base.db.page.PageView;
import com.fast.base.db.page.QueryResult;
import com.fast.base.db.sql.AbstractSqlGenerator;
import com.fast.base.model.AnoSysLog;
import com.fast.base.util.data.MathUtils;
import com.fast.base.util.web.ResponseData;
import com.fast.base.util.web.WebUtil;
import com.fast.base.web.BaseController;
import com.fast.common.userCache.AdminCacheUtils;
import com.fast.common.userCache.UserRequestUtils;
import com.fast.user.model.admin.AdminUser;
import com.fast.user.model.dept.Company;
import com.fast.user.model.dept.Department;
import com.fast.user.service.dept.DepartmentService;

/**
 * ClassName:DepartmentController <br/>
 * 用途: [部门]控制 <br/>
 * 开发人员：lushuifa  http://lushuifa.iteye.com/
 * 邮箱:lsflu@126.com
 * @version  
 * @since    JDK 1.6
 * @see
 * Date:     2014年12月17日 下午2:34:53 <br/> 	 
 */
@Controller
@RequestMapping("/department")
public class DepartmentController extends BaseController{
	

	
	@Resource(name="departmentService")
	private DepartmentService beanService;
	
	/**
	 * 得到部门下拉列表
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getDepartmentList4comboBox.do")
	public List<Department> getDepartmentList4comboBox(String parentUUID){
		List<Department> dicList =  this.beanService.queryForBeanList(Department.class, " where 1=1");
	    return dicList;
	}
	
	/**
	 * 说明:获取部门列表 <br>
	 * 编写者:lushuifa
	 * 创建时间:2017年11月15日 上午12:17:03 </pre>
	 * @param 
	 * @return List<Map<String,Object>> 说明
	 */
	@ResponseBody
	@RequestMapping("/getDeptListByCompanyUUIDForCombobox.do")
	public List<Map<String,Object>> getDeptListByCompanyUUIDForCombobox(String companyUUID) {
		List<Map<String,Object>> deptMapList = new ArrayList<Map<String,Object>>();
		List<Department> deptList = this.beanService.queryForBeanList(Department.class, "where companyUUID='"+companyUUID+"'");
		if(null!=deptList&&!deptList.isEmpty()){
			Map<String,Object> deptMap = null;
			for (Department department : deptList) {
				deptMap = new HashMap<String,Object>();
				deptMap.put("id", department.getUuid());
				deptMap.put("text", department.getDepartmentName());
				deptMapList.add(deptMap);
			}
		}
		return deptMapList;
	}
	
	/**
	 * 得到部门列表通过单位ID
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getDeptListByCompanyUUID.do")
	public List<Department> getDeptListByCompanyUUID(String companyUUID) {
		Company company = this.beanService.queryForBeanByUUID(Company.class, companyUUID);
		List<Department> deptList = new ArrayList<Department>();
		if(company!=null){
			deptList = this.beanService.queryForBeanList(Department.class, "where companyUUID='"+companyUUID+"'");
		}
		return deptList;
	}

	/**
	 * 编辑[部门]信息
	 * @param Department
	 * @return
	 */
	@RequestMapping("/editDepartment.do")
	@ResponseBody
	@AnoSysLog(actionName="编辑部门信息")
	public ResponseData editDepartment() {
		ResponseData responseData = new ResponseData();
		AdminUser curAdminUser = AdminCacheUtils.getLoginAdminUser();
		Department department = null;
		try {
			int id = webUtil.getInt("id");
			if (id > 0) {
				department = this.beanService.queryForBeanById(Department.class, id);
				department = (Department) webUtil.bindDataToBean(department);
			} else {
				department = new Department();
				department = (Department) webUtil.bindDataToBean(department);
				department.setUuid(MathUtils.getTheOnlyStr());
				department.setCreater(curAdminUser.getUserName());
				department.setCreaterId(curAdminUser.getId());
				department.setCreateTime(new Date());
			}
			// 当存在UUID时的处理
			department.setEditorId(curAdminUser.getId());
			department.setEditorName(curAdminUser.getUserName());
			department.setEditTime(new Date());
			if (this.beanService.merge(department) != null) {
				responseData.setMsg("编辑编号为[" + department.getUuid() + "]操作成功");
			}
			responseData.setCode("00");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setMsg("编辑编号为[" + department.getUuid() + "]操作失败");
		}
		return responseData;
	}
	
	/**
	 * 批量编辑[部门]信息
	 * @param formData
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editAllDepartment.do")
	@AnoSysLog(actionName="批量添加部门信息")
	public ResponseData editAllDepartment(String formData) {
		JSONArray dataList = JSONArray.parseArray(formData.replace("&quot;", "\'"));
		List<Department> deptList = JSONArray.toJavaObject(dataList, ArrayList.class);
		ResponseData responseData = new ResponseData();
		try {
			int actionCount = deptList.size();
			int success     = 0;
			int failure     = 0;
			for (Department department : deptList) {
				//设置公司名字
				String companyName = beanService.queryColumn(AbstractSqlGenerator.getTableName(Company.class), "companyName", " where uuid='"+department.getCompanyUUID()+"'").toString();
				department.setCompanyName(companyName);
				//设计唯一UUID
				department.setUuid(MathUtils.getTheOnlyStr());
				//设置操作人编辑人
				UserRequestUtils.bindCreaterInfo(department);
				UserRequestUtils.bindEditorInfo(department);
				boolean actionFlag = beanService.saveOrModify(department, " where uuid='"+department.getUuid()+"'");
				if(actionFlag){
					success++;
				}else{
					failure++;
				}
			}
		    responseData.setMsg("批量操作结果为：共添加数据["+actionCount+"],成功保存["+success+"],失败保存["+failure+"]");
			responseData.setCode("00");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setMsg("批量保存数据失败！");
		}
		return responseData;
	}
	
	/**
	 * 标题：getDepartmentList4Tree <br/>
	 * 作用： 得到部门列表，包括父类单位列表    <br/>
	 * @author developer-lushuifa
	 * @throws IOException 
	 * @since JDK 1.6
	 */
	@ResponseBody
	@RequestMapping("/getDepartmentList4Tree.do")
	public JSONArray getDepartmentList4Tree(HttpServletResponse response) throws IOException{
		List<Company> companyList = this.beanService.queryForBeanList(Company.class, " order by edit_time desc");
		//父节点
		JSONObject parentNode = new JSONObject();
		parentNode.put("id", "0");
		parentNode.put("text","单位列表");
		parentNode.put("state","open");
		parentNode.put("iconCls","icon-folderPage");
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonOBject = null;
		if(companyList.size()>0){
			for (Company company : companyList) {
				if(this.beanService.isExist(Department.class," where companyUUID='"+company.getUuid()+"'")){
				    jsonOBject = new JSONObject();
				    jsonOBject.put("id", company.getUuid());
					jsonOBject.put("text",company.getCompanyName());
					jsonOBject.put("state","closed");
					jsonOBject.put("iconCls","icon-folderPage");
					//处理部门信息
					List<Department> deptList = this.beanService.queryForBeanList(Department.class," where companyUUID='"+company.getUuid()+"' order by edit_time desc");
					JSONArray deptArray = new JSONArray();
					JSONObject dept = null;
					for (Department department : deptList) {
						dept = new JSONObject();
						dept.put("id", department.getUuid());
						dept.put("text",department.getDepartmentName());
						dept.put("iconCls","icon-page");
						deptArray.add(dept);
					}
					jsonOBject.put("children", deptArray);
					jsonArray.add(jsonOBject);
				}
			}
		}
		parentNode.put("children", jsonArray);
		JSONArray result = new JSONArray();
		result.add(parentNode);
		return result;
	}
	
	
	
	/**
	 * 得到全部[部门]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getJsonAllList.do")
	public ResponseData getDepartmentAllList(String companyUUID) {
		ResponseData responseData = new ResponseData();
		List<Department> beanList = beanService.queryForBeanList(Department.class, "where companyUUID='"+companyUUID+"' order by id desc");
		try {
			responseData.setCode("00");
			responseData.setData(beanList);
			responseData.setMsg("获取信息成功");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("获取信息失败");
		}
		return responseData;
	}
	
	/**
	 * 删除[部门]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delDepartment.do")
	@AnoSysLog(actionName="删除部门信息")
	public ResponseData delDepartment(int id) {
		ResponseData responseData = new ResponseData();
		try {
			boolean actionFlag = beanService.deleteById(Department.class, id);
			responseData.setCode(actionFlag?"00":"01");
			if(actionFlag){
				responseData.setMsg("删除部门编号为["+id+"]操作成功");
			}else{
				responseData.setMsg("删除部门编号为["+id+"]操作失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("删除部门编号为["+id+"]操作失败");
		}
		return responseData;
	}
	
	/**
	 * 删除多个[[部门]]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delMoreDepartment.do")
	@AnoSysLog(actionName="批量删除部门")
	public ResponseData delMoreDepartment(String ids) {
		ResponseData responseData = new ResponseData();
		try {
			int actionCount = beanService.deleteByIds(Department.class, ids);
			responseData.setCode("00");
			responseData.setMsg("删除[部门]编号为["+ids+"]操作成功,共成功["+actionCount+"]");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("删除[部门]["+ids+"]操作失败");
		}
		return responseData;
	}
	
	/**
	 * 得到[部门]信息
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getJsonDetail.do")
	public ResponseData getDepartmentDetail(int id) {
		ResponseData responseData = new ResponseData();
		Department bean = beanService.queryForBeanById(Department.class, id);
		try {
			responseData.setCode("00");
			responseData.setData(bean);
			responseData.setMsg("获取信息成功");
		} catch (Exception e) {
			e.printStackTrace();
			responseData.setCode("01");
			responseData.setMsg("获取信息失败");
		}
		return responseData;
	}
	
	/**
	 * 删除[部门]信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/getDepartmentDetail.do")
	public String getDepartmentDetail(int id,HttpServletRequest request,HttpServletResponse response) {
		WebUtil wu = new WebUtil(request,response);
		Department bean = beanService.queryForBeanById(Department.class, id);
		try {
			wu.setAttr("Department", bean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/admin/admin/DepartmentDetail";
	}
	
	/**
	 * 得到[部门]列表
	 * @param dtGridPager Pager对象
	 * @param request 请求对象
	 * @param response 响应对象
	 * @throws IOException 
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getDepartmentList.do", method=RequestMethod.POST)
	public Map<String,Object> getDepartmentList() {
		Map<String,Object> gridMap = new HashMap<String,Object>();
		try {
			int page = webUtil.getInt("page");//当前页
	  		int pagesize = webUtil.getInt("rows");//每页面显示多少条
	  		String companyUUID = webUtil.getString("companyUUID");
			StringBuffer sb = new StringBuffer(" where 1=1 ");
			if(!companyUUID.equals("")){
				sb.append(" and companyUUID='"+companyUUID+"'");
			}
			String ordersql = " order by orderNumber asc ";
			QueryResult<Department>  queryResult = this.beanService.queryForBeanListByPage(Department.class, sb.toString(), ordersql,(page-1)*pagesize,pagesize);
			PageView<Department> pageView = new PageView<Department>();
		    pageView.setCurrentPage(page);
			pageView.setQueryResult(queryResult);
			gridMap.put("total", pageView.getTotalRecord());
			gridMap.put("rows", pageView.getRecords());
		} catch (Exception e) {
			e.printStackTrace();
		}
 		return gridMap;
	}
}

